import React from 'react'
import { Toast } from 'antd-mobile'
import axios from 'axios'
import {List, AutoSizer} from 'react-virtualized'
import {getLocalCity} from '../../utils/localCity'
import NavHeader from '../../components/NavHeader/index'

import './index.scss'

export default class CityList extends React.Component {
  state = {
    cityList: {},
    cityIndex: [],
    activeIndex: 0,
  }

  listComponent = React.createRef()

  hasCity = ['北京', '上海', '广州', '深圳']

  formateCityList(info) {
    const cityList = {}
    info.forEach(item => {
      const key = item.short.substring(0, 1)
      if(cityList[key]) {
        cityList[key].push(item)
      } else {
        cityList[key] = [item]
      }
    })
    const cityIndex =  Object.keys(cityList).sort()
    return {
      cityList,
      cityIndex
    }
  }

  async getCityList() {
    const {data} = await axios.get('http://127.0.0.1:8080/area/city?level=1')
    if(data.status !== 200) {
      return
    }
    const {cityList, cityIndex} = this.formateCityList(data.body)

    const {data: hotdata} = await axios.get('http://127.0.0.1:8080/area/hot')
    cityList['hot'] = hotdata.body
    cityIndex.unshift('hot')
    
    const test = await getLocalCity()
    cityList['#'] = [test]
    cityIndex.unshift('#')

    this.setState({
      cityList,
      cityIndex
    })
  }

  async componentDidMount() {
    await this.getCityList()

    this.listComponent.current.measureAllRows()
  }

  componentWillUnmount() {
    this.setState({
      cityList: {},
      cityIndex: [],
    })
  }

  renderNavBar() {
    return (
      <NavHeader>城市列表</NavHeader>
    )
  }

  formateTitle(title) {
    switch(title) {
      case '#':
        return '当前定位'
      case 'hot':
        return '热门城市'
      default:
        return title.toUpperCase()
    }
  }

  rowHeight = ({index}) => {
    const {cityIndex, cityList} = this.state
    return 36 + 50 * cityList[cityIndex[index]].length
  }

  onRowsRendered = ({startIndex}) => {
    if(this.state.activeIndex !== startIndex) {
      this.setState({
        activeIndex: startIndex
      })
    }
  }

  changeCity = (label, value) => {
    if(this.hasCity.includes(label)) {
      const info = {label, value}
      localStorage.setItem('hkzf_city', JSON.stringify(info))

      this.props.history.go(-1)
    } else {
      Toast.info('您选择的城市没有数据', 2, null, false)
    }
  }

  rowRenderer = ({
    key,         
    index,  
    isScrolling, 
    isVisible,  
    style        
  }) => {
    const letter = this.state.cityIndex[index]
    const citys = this.state.cityList[letter]
    return (
      <div
          key={key}
          style={style}
          className="city-item"
      >
        <div className="title">{this.formateTitle(letter)}</div>
          {citys.map(item => {
              return (
                <div className="city" key={item.value} onClick={() => this.changeCity(item.label, item.value)}>{item.label}</div>
              )
          })}
        </div>
    )
  }

  renderCityList() {
    return (
      <>
        <AutoSizer>
          {({height, width}) => (
            <List
              ref={this.listComponent}
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.rowHeight}
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              scrollToAlignment="start"
            />
          )}
        </AutoSizer>
      </>
    )
  }

  renderCityIndex = () => {
    return (
      <ul className="city-index">
        {  
          this.state.cityIndex.map((item,index) => {
            return (
              <li className="city-index-item" key={item} onClick={()=>this.listComponent.current.scrollToRow(index)}>
                <span className={this.state.activeIndex === index? 'index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
              </li>
            )
          })
        }
      </ul>
    )
  }

  render() {
    return <div className="citylist-box">
      {this.renderNavBar()}

      {this.renderCityList()}

      {this.renderCityIndex()}
    </div>
  }
}
